package com.example.thecharacterbook;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class MyContentProvider extends ContentProvider {
    public static final String AUTHORITY = "com.example.thecharacterbook.MyContentProvider";
    public static final Uri CONTENT_URI_1=Uri.parse("content://"+AUTHORITY+"/my_BookLibrary_InTant");
    public static int MyDataBase2=1;
    static int MyDataBase_ID=2;
    SQLiteDatabase myDB;
    static  UriMatcher myUri = new UriMatcher(UriMatcher.NO_MATCH);


    static{
        myUri.addURI(AUTHORITY,"my_BookLibrary_InTant",MyDataBase2);
        myUri.addURI(AUTHORITY,"my_BookLibrary_InTant/#",MyDataBase_ID);
    }
    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int row = myDB.delete("my_BookLibrary_InTant",selection,selectionArgs);
        if(row>0){
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return row;
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long row = myDB.insert("my_BookLibrary_InTant",null,values);
        if(row>0){
            uri = ContentUris.withAppendedId(CONTENT_URI_1,row);
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return uri;
    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        MyDataBase myHelper = new MyDataBase(getContext());
        myDB = myHelper.getWritableDatabase();
        if(myDB!=null){
            return true;
        }
        else{
        return false;}
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder myQuery = new SQLiteQueryBuilder();
        myQuery.setTables("my_BookLibrary_InTant");
        Cursor cr = myQuery.query(myDB,null,selection,selectionArgs,null,null,null);
        cr.setNotificationUri(getContext().getContentResolver(),uri);
        return cr;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int row = myDB.update("my_BookLibrary_InTant",values,selection,selectionArgs);
        if(row>0){
            getContext().getContentResolver().notifyChange(uri,null);
        }
        return row;
    }
}